package com.example.emos.api.controller;

import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.*;
import com.example.emos.api.db.pojo.TbExam;
import com.example.emos.api.db.pojo.TbRank;
import com.example.emos.api.service.RankService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;

/**
 * @author ：Supyo
 * @date ：Created in 2021/11/16 14:41
 * @description：
 */
@RestController
@RequestMapping("/rank")
@Tag(name = "RankController", description = "评分标准库接口")
@Slf4j
public class RankController {
    @Autowired
    private RankService rankService;

    @PostMapping("/selectOneRank")
    @Operation(summary = "根据Id查询标准")
    public R selectOneRank(@Validated @RequestBody SelectRankByIdForm form) {
        TbRank rank = rankService.selectOneRank(form.getId());
        return R.ok().put("list", rank);
    }

    @PostMapping("/selectRankBypages")
    @Operation(summary = "标准分页查询")
    public R selectRankBypages(@Valid @RequestBody SelectRankBypagesForm form) {
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start", start);
        PageUtils pageUtils = rankService.selectRankBypages(param);
        return R.ok().put("page", pageUtils);
    }

    @PostMapping("/addRanks")
    @Operation(summary = "新增标准")
    public R addRanks(@Valid @RequestBody InsertRankForm form) {
        TbRank rank = JSONUtil.parse(form).toBean(TbRank.class);
        rank.setOptions(JSONUtil.parseArray(form.getOptions()).toString());
        rank.setCreateTime(new Date());
        int rows = rankService.addRanks(rank);
        return R.ok().put("rows", rows);
    }

    @PostMapping("/updateRank")
    @Operation(summary = "修改标准")
    public R updateRank(@Valid @RequestBody UpdateRankForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.replace("options", JSONUtil.parseArray(form.getOptions()).toString());
        int rows = rankService.updateRank(param);
        return R.ok().put("rows", rows);
    }

    @PostMapping("/deleteRanks")
    @Operation(summary = "删除标准")
    public R deleteRanks(@Valid @RequestBody DeleteRankForm form) {
        int rows = rankService.deleteRanks(form.getIds());
        return R.ok().put("rows", rows);
    }
}
